import json
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class BeijingshiBjshdqrmzfE1a6Policy(BaseTaxPolicySpider):
    name = "beijing_bjshdqrmzf_e1a6_policy"

    province: str = '北京市'  # 取表格
    city: str = '北京市'  # 取表格
    county: str = "海淀区"  # 取表格
    park: str = "None"  # 取表格
    source: str = "北京市海淀区人民政府"  # 取表格 同一个来源合并
    url: str = "https://zyk.bjhd.gov.cn/zwdt/zcml/"  # 注明入口网址，以便后续排错

    # @classmethod
    # def update_settings(cls, settings) -> None:
    #     downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
    #     new_settings = {
    #         **(cls.custom_settings or {}),
    #         **{
    #             "DOWNLOADER_MIDDLEWARES": {
    #                 "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
    #                 **downloader_middlewares
    #             }
    #         },
    #     }
    #     settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        meta = {}
        url = 'https://www.bjhd.gov.cn/sjkf-api/haidian/data/catalog/search'
        params = {
            "channelId": "76770,83277",
            "pageNum": "1",
            "pageSize": "16",
            "yearOfPublish": "",
            "youxiaoxing": "",
            "title": "",
            "zcwjfl": ""
        }
        temp_url = url + f'{"&" if "?" in url else "?"}{urllib.parse.urlencode(params)}'
        # print(temp_url)
        meta.update({"params": params, "url": url})
        yield scrapy.Request(temp_url, callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        meta = response.meta
        params = meta.get('params')
        url = meta.get('url')
        prev_item = meta.get('item')
        json_data = json.loads(response.text.strip())
        for elem in json_data['rows']:
            item = Item()
            item['source_url'] = elem['docPubUrl']
            # print(item['source_url'])
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['pubDate'].split('T')[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = math.ceil(json_data['total'] / int(params['pageSize']))
            for page_num in range(2, total_page + 1):
                params['pageNum'] = str(page_num)
                temp_url = url + f'{"&" if "?" in url else "?"}{urllib.parse.urlencode(params)}'
                meta.update({'item': prev_item, 'is_next': False, "params": params, "url": url})
                yield scrapy.FormRequest(temp_url, callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = item.get('publish_date') or response.xpath("""string(//meta[@name='PubDate']/@content)""").get().split(' ')[0]
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl beijing_bjshdqrmzf_e1a6_policy".split())
